/**
 * 过滤大量数据，优化算法
 * @param {Array} data
 * @param {Function} cb
 * @returns
 */
export const filterArray = <T>(data: Array<T>, cb: (target: T, index: number) => boolean) => {
    if (!Array.isArray(data) || !data.length) return [];

    let i = 0,
        j = data.length - 1;
    const leftData = [],
        rightData = [];

    while (true) {
        if (i > j) break;
        const left = data[i],
            right = data[j];

        if (cb(left, i)) {
            leftData.push(left);
        }

        if (i !== j && cb(right, j)) {
            rightData.unshift(right);
        }

        i++;
        j--;
    }

    return leftData.concat(rightData);
};

/**
 * 数组去重
 * @param {Array} data
 * @param {Function} cb
 * @returns
 */
export const createUniqueArray = <T>(
    data: Array<T>,
    cb?: (target: T, index: number) => boolean
) => {
    if (!Array.isArray(data)) throw '数据格式不对，请传入数组！';
    if (!cb) return Array.from(new Set(data));

    let i = 0,
        j = data.length - 1;
    const set = new Set(),
        leftData = [],
        rightData = [];

    while (true) {
        if (i > j) break;
        const left = data[i],
            right = data[j];
        const cbFromLeft = cb(left, i),
            cbFromRight = cb(right, j);

        if (!set.has(cbFromLeft)) {
            leftData.push(left);
            set.add(cbFromLeft);
        }

        if (i !== j && !set.has(cbFromRight)) {
            rightData.unshift(right);
            set.add(cbFromRight);
        }

        i++;
        j--;
    }

    return leftData.concat(rightData);
};
